<!DOCTYPE html>
<html lang="zh">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <input type="file" id="file">
  <script>
    function request({
      url,
      method = 'POST',
      data,
      headers = {},
      requestList
    }) {
      return new Promise(resolve => {
        var xhr = new XMLHttpRequest()
        xhr.open(method, url)
        Object.keys(headers).forEach(key => {
          xhr.setRequestHeader(key, headers[key])
        })
        xhr.send(data)
        xhr.onload = e => {
          resolve({
            data: e.target.response
          })
        }
      })
    }
    file.addEventListener('change', async event => {
      const file = event.target.files[0]
      const file_name = file.name.split('.')[0]
      console.log(file)
      var cur = 0, size = 1024 * 1024 // 1M
      const fileChunkList = []
      while (cur < file.size) {
        fileChunkList.push({
          file: file.slice(cur, cur + size)
        })
        cur += size
      }
      console.log(fileChunkList);
      const requestList = fileChunkList.map(({ file }, index) => {
        const formdata = new FormData()
        console.log(file);
        formdata.append('file', file)
        formdata.append(`${file_name}-${index}`, file)
        // formdata.append(`chunk`, file)
        // formdata.append('filename', `${file_name}-${index}`)
        return { formdata }
      }).map(async ({ formdata }) => request({
        url: 'http://127.0.0.1:3001',
        data: formdata
      }))
      await Promise.all(requestList)
    })
  </script>
</body>

</html>